/*
 * synthesiser.cu
 *
 *  Created on: Sep 30, 2011
 *      Author: kunu
 */

#include <cuda.h>
#include <cutil.h>
//#include <math.h>

#include "oscillators.h"
#include "globals.h"

int init_DeviceMem(float **buf_d, size_t buf_d_size_in_bytes) {
	cudaMalloc((void**) buf_d, buf_d_size_in_bytes);
	cudaMemset(*buf_d, 0, buf_d_size_in_bytes);
	return 0;
}

int syn_launcher(data_bundle *d, pthread_cond_t *kill_rt_player_cond) {
	int count = 0;
	int N = SAMPLE_SIZE;
	do {
		pthread_mutex_lock((d->buf_d_slot_mutex[d->NFS]));
		while (d->buf_d_status[d->NFS] == SLOT_FILLED) {
			pthread_cond_wait(d->notFull, d->buf_d_slot_mutex[d->NFS]);
		}
		// fill buffer
//		printf(" << filling slot[%d] >>\n", d->NFS);
		synthesiser_dispatch(d->buf_d_slot[d->NFS], N, d->sidx);
//		for(int i=0; i<SAMPLE_SIZE; i++) {
//			d->buf_d_slot[d->NFS][i] = sinf((d->sidx+i)*2*M_PI/44100* 600);
//		}
		d->sidx += N;
		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		d->buf_d_status[d->NFS] = SLOT_FILLED;
		pthread_cond_signal(d->notEmpty);
		pthread_mutex_unlock((d->buf_d_slot_mutex[d->NFS]));
		d->NFS++;
		d->NFS %= NUM_SLOTS;
		count++;
	} while (count < (44100*10/SAMPLE_SIZE));
	pthread_cond_signal(kill_rt_player_cond);
	return 0;
}

int devToHostCopier(float *buf_play_l, float *buf_play_r, float *buf_d, unsigned int nBufferFrames ) {
	cudaMemcpy(buf_play_l, buf_d, nBufferFrames*sizeof(float), cudaMemcpyDeviceToHost);
	cudaMemcpy(buf_play_r, buf_d, nBufferFrames*sizeof(float), cudaMemcpyDeviceToHost);
//	memcpy(buf_play_r, buf_play_l, nBufferFrames*sizeof(float));
	return 0;
}
